package org.dong.samples.web;

import java.text.ParseException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpSession;
import org.dong.samples.model.vo.MessageVO;
import org.dong.samples.service.ManageStudentService;
import org.dong.samples.util.ExcelUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Controller
public class FileUploadController {
	
	@Autowired
	private ManageStudentService manageStudentService;
	
	
	@RequestMapping(value = "/upload")
	public @ResponseBody MessageVO upload(@RequestParam(value = "uploadFile", required = false) MultipartFile[] uploadFile, HttpSession session, ModelMap model) throws ParseException{
		MessageVO message = new MessageVO();
//		String path = session.getServletContext().getRealPath("upload");
		MultipartFile uploadSimpleFile = uploadFile[0];
		String fileName = uploadSimpleFile.getOriginalFilename();
		String pos = fileName.substring(fileName.lastIndexOf("."));
		Map<String, String> messageMap = new HashMap<String, String>();
		try {
			if(ExcelUtils.OFFICE_EXCEL_2007_POX.equals(pos) || ExcelUtils.OFFICE_EXCEL_2003_POX.equals(pos)){
				manageStudentService.saveStudentByExcel(uploadSimpleFile.getInputStream(), pos);
				message.setSuccess(true);
			}else{
				messageMap.put("message", "文件格式不正确");
				message.setMessageMap(messageMap);
			}
		} catch (Exception e) {
			e.printStackTrace();
			messageMap.put("message", "批量导入失败");
			message.setMessageMap(messageMap);
		}
		return message;
	}
}
